package cashback

import (
	"fmt"
	"time"
)

// CashbackType 返现类型
type CashbackType string

const ( //返现分两种
	ShareCashback       CashbackType = "share"       // 分享返现
	InstallmentCashback CashbackType = "installment" // 分期返现
)

// CashbackRecord 返现记录结构体
type CashbackRecord struct {
	UserID      uint         // 用户ID
	Amount      float64      // 返现金额
	Type        CashbackType // 返现类型
	RecordDate  time.Time    // 记录时间
	Description string       // 描述信息
	Year        int          // 第几年(分期返现专用)
	MonthlyFee  float64      // 月费(分期返现专用)
	ShareAmount float64      // 分享产生的金额(分享返现专用)
}

// CashbackRecordManager 用于管理所有的返现记录
type CashbackRecordManager struct {
	records []CashbackRecord //包含一个 records 切片，存储所有的 CashbackRecord
}

// NewCashbackRecordManager 创建新的返现记录管理器
func NewCashbackRecordManager() *CashbackRecordManager {
	return &CashbackRecordManager{
		records: make([]CashbackRecord, 0),
	}
}

// AddShareCashbackRecord 添加分享返现记录
func (m *CashbackRecordManager) AddShareCashbackRecord(userID uint, shareAmount float64, cashbackAmount float64) {
	record := CashbackRecord{
		UserID:      userID,
		Amount:      cashbackAmount,
		Type:        ShareCashback,
		RecordDate:  time.Now(),
		Description: "分享用户产生的返现",
		ShareAmount: shareAmount,
	}
	m.records = append(m.records, record)
}

// AddInstallmentCashbackRecord 添加分期返现记录
func (m *CashbackRecordManager) AddInstallmentCashbackRecord(userID uint, year int, monthlyFee float64, cashbackAmount float64) {
	record := CashbackRecord{
		UserID:      userID,
		Amount:      cashbackAmount,
		Type:        InstallmentCashback,
		RecordDate:  time.Now(),
		Description: fmt.Sprintf("第%d年分期返现", year),
		Year:        year,
		MonthlyFee:  monthlyFee,
	}
	m.records = append(m.records, record)
}

// GetRecordsByType 根据类型获取返现记录
func (m *CashbackRecordManager) GetRecordsByType(recordType CashbackType) []CashbackRecord {
	var result []CashbackRecord
	for _, record := range m.records {
		if record.Type == recordType {
			result = append(result, record)
		}
	}
	return result
}

// GetRecordsByUser 获取指定用户的返现记录
func (m *CashbackRecordManager) GetRecordsByUser(userID uint) []CashbackRecord {
	var result []CashbackRecord
	for _, record := range m.records {
		if record.UserID == userID {
			result = append(result, record)
		}
	}
	return result
}

// GetTotalCashbackAmount 获取用户总返现金额
func (m *CashbackRecordManager) GetTotalCashbackAmount(userID uint) float64 {
	var total float64
	for _, record := range m.records {
		if record.UserID == userID {
			total += record.Amount
		}
	}
	return total
}
